package anji.plus.system.mark.controller;

import java.io.IOException;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;

import anji.plus.system.mark.base.Header;
import anji.plus.system.mark.base.IBaseService;
import anji.plus.system.mark.base.BaseController;
import anji.plus.system.mark.domain.SysUser;
import anji.plus.system.mark.domain.TaskList;
import anji.plus.system.mark.domain.TaskNodeList;
//import anji.plus.system.mark.dto.TaskListAndNode;
import anji.plus.system.mark.dto.RankInfo;
import anji.plus.system.mark.exception.BusinessException;
import anji.plus.system.mark.response.ResponseResult;
import anji.plus.system.mark.service.ITaskListService;
import anji.plus.system.mark.utils.LoginUtils;
import anji.plus.system.mark.vo.*;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 任务表 前端控制器
 * </p>
 *
 * @author luwei
 * @since 2023-11-08
 */
@RestController
@RequestMapping("sys/task")
public class TaskListController extends BaseController {

    @Resource
    private ITaskListService taskListService;

    @Override
    public IBaseService getService() {
        return null;
    }

    @Resource
    LoginUtils loginUtils;

    @Resource
    protected HttpServletRequest request;

    Map<String, Integer> map = new HashMap<>();

    // 查询 任务列表-按姓名和年月查询
    @GetMapping({"list"})
    public ResponseResult queryTaskList(String name, String year, String month, String departNum) {

        LocalDate monthFirstDay = LocalDate.of(Integer.parseInt(year), Integer.parseInt(month), 1);
        //当月第一天
//        System.out.println(monthFirstDay);
        // 获取指定日期的最后一天
        LocalDate lastDayOfMonth = monthFirstDay.with(TemporalAdjusters.lastDayOfMonth());
        LocalDate nextMonthfirstday = lastDayOfMonth.plusDays(1);
        //次月第一天
//        System.out.println(nextMonthfirstday);

        List<TaskList> taskList = taskListService.queryTaskList(name, monthFirstDay, nextMonthfirstday,departNum);
        return ResponseResult.success(taskList);
    }


    // 新增 任务
    @PostMapping({"addTask"})
    public ResponseResult addTask(@RequestBody TaskListVo taskListVo) {
//        if (taskListVo.getScheduleTime() == null)
        taskListService.addTask(taskListVo);
        return ResponseResult.success("新增成功");

    }

    // 任务确认 审核

    @PostMapping({"taskConfirmReview"})
    //任务状态 1：任务确认待审核； 2：任务确认审核驳回；3：任务确认审核通过（进行中）；5. 任务完成待审核（已完成）；
    // 6： 任务完成审核驳回；7：任务完成审核通过；
    public ResponseResult ConfirmReview(String taskId, String confirmReviewUser, String reviewStatus, String confirmReason,String confirmChangeMark,String changeReviewUser,String isChange) {
        if (confirmReviewUser == null ) {
            return ResponseResult.failure("请正确填写有效信息");
        }else if (confirmReviewUser == "") {
            return ResponseResult.failure("请正确填写有效信息");

        }else if (reviewStatus.equals("2")) {
            TaskList taskList = taskListService.ConfirmReviewFail(taskId, confirmReviewUser, reviewStatus, confirmReason,isChange);
            return ResponseResult.success(taskList);

        } else if (reviewStatus.equals("3")) {
            TaskList taskList = taskListService.ConfirmReviewPass(taskId, confirmReviewUser, reviewStatus, confirmReason,isChange);
            return ResponseResult.success(taskList);
        } else if (reviewStatus.equals("1")) {
            TaskList taskList = taskListService.ConfirmChange(taskId,changeReviewUser, reviewStatus, confirmChangeMark, isChange);
            return ResponseResult.success(taskList);
        }else {

            return ResponseResult.failure("提交失败，请联系管理员");
        }
    }

    // 更新,提交 任务
    @PostMapping({"taskUpdate"})
    public ResponseResult taskUpdate(@RequestBody TaskListVoUpdate taskListVoUpdate) {
        taskListService.taskUpdate(taskListVoUpdate);
        return ResponseResult.success("更新成功");

    }

    // 任务完成 审核
    @PostMapping({"completeReview"})
    public ResponseResult completeReview(String taskId, String completeReviewUser, String reviewStatus, String completeReason, String completeChangeMark, String changeReviewUser, String isChange) {
        if (reviewStatus.equals("6")) {
            TaskList taskList = taskListService.completeReviewFail(taskId, completeReviewUser, reviewStatus, completeReason,isChange);
            return ResponseResult.success(taskList);

        }else if (reviewStatus.equals("7")) {
            TaskList taskList = taskListService.completeReviewPass(taskId, completeReviewUser, reviewStatus, completeReason,isChange);
            return ResponseResult.success(taskList);
        } else if (reviewStatus.equals("5")) {
            TaskList taskList = taskListService.completeChange(taskId,changeReviewUser, reviewStatus, completeChangeMark, isChange);
            return ResponseResult.success(taskList);
        }else {

            return ResponseResult.failure("提交失败，请联系管理员");
        }

    }

    //
    // 查询 审核
    @GetMapping({"reviewList"})
    public ResponseResult reviewList(String name, String menuStatus) {
        if (menuStatus.equals("1")) {
            //  需审核
            List<TaskList> taskList = taskListService.queryNeedReviewTask(name);
            return ResponseResult.success(taskList);

        } else if (menuStatus.equals("2")) {
            //  待审核
            List<TaskList> taskList = taskListService.queryWaitReviewTask(name);
            return ResponseResult.success(taskList);
        } else if (menuStatus.equals("3")) {
            //   已驳回
            List<TaskList> taskList = taskListService.queryRejectTask(name);
            return ResponseResult.success(taskList);
        } else {

            return ResponseResult.failure("查询失败，请联系管理员");
        }

    }

    // 查询个人得分
    @GetMapping({"userScore"})
    public ResponseResult queryUserScore(String name, String year, String month) {

        LocalDate monthFirstDay = LocalDate.of(Integer.parseInt(year), Integer.parseInt(month), 1);
        //当月第一天
//        System.out.println(monthFirstDay);
        // 获取指定日期的最后一天
        LocalDate lastDayOfMonth = monthFirstDay.with(TemporalAdjusters.lastDayOfMonth());
        LocalDate nextMonthfirstday = lastDayOfMonth.plusDays(1);
        //次月第一天
//        System.out.println(nextMonthfirstday);
        return ResponseResult.success(taskListService.queryUserScore(name,monthFirstDay,nextMonthfirstday));

    }

    // 查询个人任务数
    @GetMapping({"userTaskNum"})
    public ResponseResult queryUserTaskNum(String name, String year, String month) {

//        LocalDate localDate = LocalDate.now();
//        //当月第一天
//        localDate = localDate.withDayOfMonth(1);
//        //当月最后天
//        LocalDate lastDayOfMonth1 = localDate.with(TemporalAdjusters.lastDayOfMonth());
//        //次月第一天
//        LocalDate nextMonthfirstday = lastDayOfMonth1.plusDays(1);
//
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//        String monthFirstDate = localDate.format(formatter);
//        String nextMonthday = nextMonthfirstday.format(formatter);
        LocalDate monthFirstDay = LocalDate.of(Integer.parseInt(year), Integer.parseInt(month), 1);
        //当月第一天
//        System.out.println(monthFirstDay);
        // 获取指定日期的最后一天
        LocalDate lastDayOfMonth = monthFirstDay.with(TemporalAdjusters.lastDayOfMonth());
        LocalDate nextMonthfirstday = lastDayOfMonth.plusDays(1);
        //次月第一天
//        System.out.println(nextMonthfirstday);

        return ResponseResult.success(taskListService.queryUserTaskNum(name,monthFirstDay,nextMonthfirstday));

    }

    // 查询个人积分排名
    @GetMapping({"userScoreRank"})
    public ResponseResult userScoreRank(String year, String month) {

        LocalDate monthFirstDay = LocalDate.of(Integer.parseInt(year), Integer.parseInt(month), 1);
        //当月第一天
//        System.out.println(monthFirstDay);
        // 获取指定日期的最后一天
        LocalDate lastDayOfMonth = monthFirstDay.with(TemporalAdjusters.lastDayOfMonth());
        LocalDate nextMonthfirstday = lastDayOfMonth.plusDays(1);
        //次月第一天
//        System.out.println(nextMonthfirstday);

        return ResponseResult.success(taskListService.userScoreRank(monthFirstDay,nextMonthfirstday));

    }

    // 查询 微信首页-查询
    @GetMapping({"personQuery"})
    public ResponseResult personQuery(String name, String year, String month, String departNum){

        LocalDate monthFirstDay = LocalDate.of(Integer.parseInt(year), Integer.parseInt(month), 1);
        //当月第一天
//        System.out.println(monthFirstDay);
        // 获取指定日期的最后一天
        LocalDate lastDayOfMonth = monthFirstDay.with(TemporalAdjusters.lastDayOfMonth());
        LocalDate nextMonthfirstday = lastDayOfMonth.plusDays(1);

        return ResponseResult.success(taskListService.indexQuery(name,monthFirstDay,nextMonthfirstday,departNum));
    }

    // 查询个人是否存在需审核记录
//    @Anonymous
    @GetMapping({"userAuditTask"})
    public ResponseResult userAuditTask(String name) {

        List<TaskList> taskList = taskListService.queryNeedReviewTask(name);
        String a1 = "1";
        String a0 = "0";
        if (String.valueOf(taskList.size()).equals(a0)){
            return ResponseResult.success((Object)a0);
        }else{
            return ResponseResult.success((Object)a1);
        }


    }

    // 任务完成 审核-NEW
    @PostMapping({"completeReviewPass"})
    public ResponseResult completeReviewPass(@RequestBody TaskListVoCompleteUpdate taskListVoCompleteUpdate) {
        if (taskListVoCompleteUpdate.getReviewStatus().equals("6")) {
            TaskList taskList = taskListService.completeReviewFail(String.valueOf(taskListVoCompleteUpdate.getTaskId()), taskListVoCompleteUpdate.getCompleteReviewUser(), taskListVoCompleteUpdate.getReviewStatus(),taskListVoCompleteUpdate.getCompleteReason(),taskListVoCompleteUpdate.getIsChange());
            return ResponseResult.success(taskList);

        }else if (taskListVoCompleteUpdate.getReviewStatus().equals("7")) {
            //更新主任务
            TaskList taskList = taskListService.completeReviewPass(String.valueOf(taskListVoCompleteUpdate.getTaskId()), taskListVoCompleteUpdate.getCompleteReviewUser(), taskListVoCompleteUpdate.getReviewStatus(),taskListVoCompleteUpdate.getCompleteReason(),taskListVoCompleteUpdate.getIsChange());
            //更新子任务进度
            taskListService.NodeCompleteUpdate(taskListVoCompleteUpdate);
            //更新主任务得分
            taskListService.scoreUpdate(taskListVoCompleteUpdate);
            return ResponseResult.success(taskList);
            //1 根据ID查询子节点信息；
        } else if (taskListVoCompleteUpdate.getReviewStatus().equals("5")) {
            if(taskListVoCompleteUpdate.getChangeReviewUser() == null){
                return ResponseResult.failure("流转人不能为空");
            }else if(taskListVoCompleteUpdate.getCompleteChangeMark() == null){
                return ResponseResult.failure("流转原因不能为空");
            }
            TaskList taskList = taskListService.completeChange(String.valueOf(taskListVoCompleteUpdate.getTaskId()), taskListVoCompleteUpdate.getChangeReviewUser(), taskListVoCompleteUpdate.getReviewStatus(),taskListVoCompleteUpdate.getCompleteChangeMark(),taskListVoCompleteUpdate.getIsChange());
            return ResponseResult.success(taskList);
        }else {

            return ResponseResult.failure("提交失败，请联系管理员");
        }

    }

    // 查询个人积分排名-new
    @GetMapping({"userScoreRank2"})
    public ResponseResult userScoreRank2(String year, String month, String departNum) {

        LocalDate monthFirstDay = LocalDate.of(Integer.parseInt(year), Integer.parseInt(month), 1);
        //当月第一天
//        LocalDate monthMidDay = LocalDate.of(Integer.parseInt(year), Integer.parseInt(month), 15);
//        System.out.println(monthFirstDay);
        // 获取指定日期的最后一天
        LocalDate lastDayOfMonth = monthFirstDay.with(TemporalAdjusters.lastDayOfMonth());
        LocalDate nextMonthfirstday = lastDayOfMonth.plusDays(1);
        //次月第一天
//        System.out.println(nextMonthfirstday);

//        return ResponseResult.success(taskListService.userScoreRank(monthFirstDay,nextMonthfirstday));
        return ResponseResult.success(taskListService.userScoreRank2(monthFirstDay,nextMonthfirstday,departNum));
    }


    // 查询 PC首页-查询
    @GetMapping({"personQueryPC"})
    public ResponseResult personQueryPC(String name, String year, String month, String departNum){

        LocalDate monthFirstDay = LocalDate.of(Integer.parseInt(year), Integer.parseInt(month), 1);
        //当月第一天
//        System.out.println(monthFirstDay);
        // 获取指定日期的最后一天
        LocalDate lastDayOfMonth = monthFirstDay.with(TemporalAdjusters.lastDayOfMonth());
        LocalDate nextMonthfirstday = lastDayOfMonth.plusDays(1);

        return ResponseResult.success(taskListService.indexQuerypc(name,monthFirstDay,nextMonthfirstday,departNum));
    }



//    @GetMapping({"export"})
//    public void exportExcel(HttpServletResponse response, RankInfo rankInfo){
//        try {
//            LambdaQueryWrapper<RankInfo> queryWrapper= Wrappers.lambdaQuery();
//            queryWrapper.like(!ObjectUtils.isEmpty(rankInfo.getCity()),rankInfo::getCity,rankInfo.getCity());
//            List<RankInfo> list= taskListService.list(queryWrapper);
//            String fileName = URLEncoder.encode("网址列表", "UTF-8").replaceAll("\\+", "%20");
//            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
//            try {
//                EasyExcel.write(response.getOutputStream())
//                        .head(Website.class)
//                        .sheet("网址列表")
//                        .doWrite(list);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        } catch (IOException e) {
//            Logger log;
//            log.info("网址列表导出异常：{}", e.getMessage());
//            throw new BusinessException("导出异常");
//        }
//    }
}

